# -*- coding:utf-8 -*-
"""
Created on Jul 28, 2011

@author: Oberron
@attention: http://www.calconnect.org/tests/iCalendar-RRULE-Interop/iCalendar-RRULE-Interop-Matrix.html
@attention: http://www.calconnect.org/tests/recurr_ical_streams.doc
@version: 0.3
@change: 0.1->0.2: update for python 2.7 in concurence with GAE migration to python 2.7
@change: 0.2->0.3: udpate for ical now returning date or datetime
"""

import webapp2
import ical
import datetime
import wsgiref.handlers
import json
import urllib2
import logging

class Entry(webapp2.RequestHandler):
    def get(self):
        self.response.out.write("""<html><head><title>iCalculator</title>
            <link rel="stylesheet" href="/dev/themes/base/jquery.ui.all.css">
            <script src="/dev/jquery-1.7.1.js"></script>
            <script src="/dev/ui/jquery.ui.core.js"></script>
            <script src="/dev/ui/jquery.ui.widget.js"></script>
            <script src="/dev/ui/jquery.ui.datepicker.js"></script>
            <link rel="stylesheet" href="/dev/demos/demos.css">
            <link rel="stylesheet" href="/dev/buttons.css" type="text/css" /> 
            <link rel="stylesheet" href="/dev/header.css" type="text/css" />
            <link rel="stylesheet" href="/dev/content.css" type="text/css" /> 
            <script>
            $(function() {
            $( "#datepicker_start" ).datepicker({ dateFormat: 'yymmdd' });
            $( "#datepicker_stop" ).datepicker({ dateFormat: 'yymmdd' });
            
            });
            </script>
            <script type="text/javascript">
            function loadXMLDoc()
            {
            $.post("/load",
            { content: document.getElementById('ical').value,start:document.getElementById('datepicker_start').value,end:document.getElementById('datepicker_end').value},
            function(data){
                //alert("Data Loaded: "+data);
            	document.getElementById('myDiv').innerHTML =""
                document.getElementById('myDiv').innerHTML = data;
              }
              );
              }
            </script>
            
            </head><body>
            <div id="header">
            <img id="logo" src="/dev/logo.png" alt="1-annum.com" /> <h2>ICalculator </h2>-  Icalendar date calculator
            <ul id="buttons">
            <li class="nicebutton" href="faq.php?lang=en">About</li>
            <li class="nicebutton" href="calconf.php?lang=en">Tour</li>
            </ul>             			
            </div>
        """)

        self.response.out.write("""
            <p> web interface for the <a href="http://pypi.python.org/pypi/pyICSParser">pyICSParser</a> library </p>
            <h2> enter below your ICALENDAR file </h2>
              <!-- form action="/load" method="post" -->
                <div><textarea name="content" rows="17" cols="60" id="ical"></textarea></div>
            Enter here the start date: <div><input name="start" rows="1" cols="8" value="20120101" id="datepicker_start"></input></div>
            Enter here the start date: <div><input name="stop"  rows="1" cols="8" value="20121231" id="datepicker_end"></input></div>
                
                <div><input type="submit" value="Get dates within selected range" onclick="loadXMLDoc()"></div>
                <div id="myDiv"><h2>Results to be displayed here</h2></div>
              <!-- /form -->
            </body>
            </html>""")        
        
class Calculate(webapp2.RequestHandler):
    def post(self):
        content = self.request.get('snippet')
        file = self.request.get('file')
        url = self.request.get('url')
        start = self.request.get('start')
        end = self.request.get('end')
        logging.debug("content is : %s, url is: %s"%(content, url))
        if len(content)>1:
            sical = content
        elif len(url)>1:
            #https://www.google.com/calendar/ical/vs3nme9en4b27le06q1bg6t9mc%40group.calendar.google.com/private-a4cbce0607cdfe85262251a6c631c1dc/basic.ics
            response = urllib2.urlopen(url)
            sical = response.read()
        else:
            sical = content
        if len(start)<8:
            start="20120101"
        if len(end)<8:
            end="20121231"
        sical = sical.replace("\r","\n").replace("\n\n","\n")
        mycal = ical.ics()
        ver = mycal.version
        mycal.ical_data = []
        mycal.string_load(sical)
        dates = mycal.get_event_instances(start,end)

        #http://stackoverflow.com/questions/455580/json-datetime-between-python-and-javascript
        dthandler = lambda obj: obj.isoformat() if (isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date)) else None
        sdates = json.dumps(dates,default=dthandler)
        if len(dates)<1:
            #dates = "No dates returned at"+str(datetime.datetime.now())+"file was:"+file+"url was:"+url
            sdates = "{\"debug "+ver+" \":\"" + url+"\"}"
            #dates = mycal.debug_string
        self.response.out.write(sdates)
        #self.response.out.write('test')

        
        
class Debug(webapp2.RequestHandler):
    def get(self):
        self.response.out.write('<html><head><title>ICS debug</title></head><body>TEST PaGE')
        self.response.out.write('</body></html>')
  
app = webapp2.WSGIApplication([
  ('/ical/', Entry),
  ('/load', Calculate),
  ('/debug',Debug),
], debug=True)

"""
def main():
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
"""